﻿using AdminWeb.Areas.Sys.Models;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using NPOI.SS.Formula.Functions;
using SqlSugar;
using XW.Core;
using XW.Data;
using XW.Utils;
using XW.Web.Framework;

namespace AdminWeb.Areas.Sys.Controllers
{
    [Area("Sys")]
    [Authorize]
    public class PosController : BaseController
    {
        private readonly SqlSugarRepository<SysPos> _posRep;
        private readonly ILogger<OrgController> _logger;
        public PosController(ILogger<OrgController> logger, SqlSugarRepository<SysPos> posRep)
        {
            this._posRep = posRep;
            this._logger = logger;
        }
        public IActionResult List()
        {
            return View();
        }
        /// <summary>
        /// 分页查询
        /// </summary>
        /// <returns></returns>
        public async Task<IActionResult> PageAsync()
        {
            var pageModel = CommonHelper.GetPageModel4Form<UserPageModel>();
            RefAsync<int> count = 0;
            var query = _posRep.AsQueryable();
            pageModel.Keyword = pageModel.Keyword.SafeTrim();
            // 关键字查询
            query.WhereIF(pageModel.Keyword.IsNotNullAndEmpty(),
                u => u.Name.Contains(pageModel.Keyword));

            // 排序
            if (pageModel.SortField.IsNotNullAndEmpty())
            {
                query.OrderByPropertyName(pageModel.SortField, pageModel.SortType == "desc" ? OrderByType.Desc : OrderByType.Asc);
            }
            // 排序
            var list = await query.ToPageListAsync(pageModel.Page, pageModel.Limit, count);

            return GetSuccessResult(new { items = list, count = count.Value });
        }


        /// <summary>
        /// 编辑
        /// </summary>
        /// <returns></returns>
        public IActionResult Edit(long id = 0)
        {
            SysPos pos = null;
            if (id > 0)
            {
                pos = _posRep.GetById(id);
                if (pos == null)
                {
                    return Content("<h1>数据不存在！</h1>");
                }
            }
            else
            {
                pos = new SysPos();
            }

            //ViewData["CurrentUser"] = user;
            return View(pos);
        }

        /// <summary>
        /// 保存
        /// </summary>
        /// <returns></returns>
        [Authorize]
        public IActionResult Save()
        {
            string? Name = this.Request.Form["Name"];
            string? Code = this.Request.Form["Code"];
            string Remark = this.Request.Form["Remark"]; 
            int Status = CommonHelper.ToInt(this.Request.Form["Status"]); 
            int Sort = CommonHelper.ToInt(this.Request.Form["Sort"]);  // 排序
            long id = CommonHelper.ToInt64(this.Request.Form["id"]);
            if (Name.IsNullOrEmpty())
            {
                return GetErrorResult("角色名不能为空");
            }
            if (id == 0)
            {
                var pos = new SysPos();
                pos.Name = Name;
                pos.Code = Code;
                pos.Remark = Remark;
                pos.Status = Status; 
                pos.Sort = Sort;
                pos.IsDelete = false;
                _posRep.Insert(pos);
            }
            else
            {
                _posRep.AsUpdateable()
               .SetColumns(u => u.Code == Code)
               .SetColumns(u => u.Name == Name)
               .SetColumns(u => u.Remark == Remark)
               .SetColumns(u => u.Status == Status)
               .SetColumns(u => u.Sort == Sort)
               .setColumnsUpdateUserAndTime()
               .Where(u => u.Id == id).ExecuteCommand();
            }

            return GetSuccessResult("保存成功！");

        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <returns></returns>
        [Authorize]
        public async Task<IActionResult> Delete(long id = 0)
        {
            var pos = _posRep.GetById(id);
            if (pos == null)
            {
                return GetErrorResult("数据不存在");
            }
            var result = await _posRep.DeleteByIdAsync(id);

            return GetSuccessResult("操作成功！");
        }
        /// <summary>
        /// 批量删除
        /// </summary>
        /// <returns></returns>
        [Authorize]
        public async Task<IActionResult> BatDelete()
        {
            string ids = Request.Form["ids"];
            if (ids.IsNullOrEmpty())
            {
                return GetErrorResult("请选择需要删除的数据");
            }
            var idlist = ids.Split(',').Select(d => CommonHelper.ToInt64(d)).ToArray();
            var result = await _posRep.DeleteAsync(d => idlist.Contains(d.Id));
            return GetSuccessResult("操作成功！");
        }
    }
}
